package com.qsl.ssyx.payment.api;


import com.qsl.ssyx.common.exception.BusinessException;
import com.qsl.ssyx.common.result.Result;
import com.qsl.ssyx.common.result.ResultCodeEnum;
import com.qsl.ssyx.payment.service.PaymentInfoService;
import com.qsl.ssyx.payment.service.WXPaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 * 支付信息表 前端控制器
 * </p>
 *
 * @author 青衫泪
 * @since 2023-09-11
 */
@Api(tags = "微信支付接口")
@RestController
@RequestMapping("/api/payment/weixin")
public class WXPaymentApiController {

    @Autowired
    private WXPaymentService wxPaymentService;


    @ApiOperation("根据订单号支付-JSAPI支付")
    @GetMapping("createJsapi/{orderNo}")
    public Result createJsapi(@ApiParam(value = "订单号", required = true)
                              @PathVariable String orderNo) {
        Map<String, String> map = wxPaymentService.createJsapi(orderNo);
        return Result.ok(map);
    }

    @ApiOperation("根据订单号调用微信接口查询支付状态-是否支付成功")
    @GetMapping("queryPayStatus/{orderNo}")
    public Result queryPayStatus(@ApiParam(value = "订单号", required = true)
                                 @PathVariable String orderNo) {
        // 根据订单号调用微信接口查询支付状态
        Map<String, String> resultMap = wxPaymentService.queryPayStatus(orderNo);
        // 判断是否支付成功，
        if (resultMap == null) { // 支付失败
            return Result.build(null, ResultCodeEnum.PAYMENT_FAIL);
        } else if (resultMap.get("trade_state").equals("SUCCESS")) { //  支付成功： 修改支付记录状态（已经支付），修改订单记录（减库存）
            String outTradeNo = resultMap.get("out_trade_no"); // 商品号
            wxPaymentService.paySuccess(outTradeNo, resultMap);
        } else { // 支付中,等待  ==>  定时器，每隔3秒查询是否支付成功
            wxPaymentService.payTimer();
        }
        return null;
    }
}

